import sys
import os
from pathlib import Path
import inspect
import json
libpath=(str(Path(inspect.getsourcefile(lambda:0)).parent.parent.resolve()))
sys.path.insert(0,libpath)

import brower.import_libpath
from selenium import webdriver
from selenium.common.exceptions import NoSuchWindowException
from urllib.parse import urlparse,urlencode
from pathlib import Path
from vim_server import generate_vim_url
class WebBrower:
    driver=None

    def openUrl(self,url,parms=''):
        targetUrl=urlparse(url)
        if targetUrl.scheme is None or targetUrl.scheme == '':
            if(url.startswith('~')):
                targetUrl=Path(url).expanduser()
            else:
                targetUrl=Path(url).resolve()
            targetUrl=generate_vim_url(targetUrl)
        else:
           targetUrl=url
        if self.driver is None :
           self.driver=webdriver.Chrome()
        is_empty=parms == '' or parms is None
        if not is_empty:
            targetUrl=targetUrl+'?'+urlencode(json.loads(parms))
        try:
            self.driver.get(targetUrl)
        except Exception as e:
            print(f'{e}')
            self.driver=None
            self.openUrl(url,parms=parms)


    def close(self):
        if self.driver is not None:
            try:
                self.driver.close()
            finally:
                self.driver=None

if __name__ == "__main__":
    webBrower=WebBrower()
else:
    pass
